<template>
  <div class="tag-selector">
    <div class="tag-selector-header">
      <h3>选择标签</h3>
      <el-button type="text" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新建标签
      </el-button>
    </div>
    
    <!-- 搜索栏 -->
    <div class="tag-search">
      <el-input
        v-model="searchQuery"
        placeholder="搜索标签..."
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    
    <!-- 标签列表 -->
    <div class="tag-list" v-loading="loading">
      <div
        v-for="tag in filteredTags"
        :key="tag.id"
        class="tag-item"
        :class="{ 'tag-selected': selectedTags.includes(tag.id) }"
        @click="toggleTagSelection(tag.id)"
      >
        <div class="tag-color" :style="{ backgroundColor: tag.color }"></div>
        <div class="tag-name">{{ tag.name }}</div>
        <div class="tag-check">
          <el-icon v-if="selectedTags.includes(tag.id)">
            <Check />
          </el-icon>
        </div>
      </div>
      
      <!-- 空状态 -->
      <EmptyState
        v-if="!loading && filteredTags.length === 0"
        type="tag"
        description="没有找到标签"
      >
        <el-button type="primary" @click="showCreateDialog">
          创建第一个标签
        </el-button>
      </EmptyState>
    </div>
    
    <!-- 已选择的标签 -->
    <div class="selected-tags" v-if="selectedTags.length > 0">
      <div class="selected-tags-header">
        <span>已选择 ({{ selectedTags.length }})</span>
        <el-button type="text" @click="clearSelection">清除</el-button>
      </div>
      <div class="selected-tag-list">
        <div
          v-for="tagId in selectedTags"
          :key="tagId"
          class="selected-tag-item"
        >
          <div
            class="tag-color"
            :style="{ backgroundColor: getTagById(tagId)?.color }"
          ></div>
          <span class="tag-name">{{ getTagById(tagId)?.name }}</span>
          <el-button type="text" @click="removeTag(tagId)">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="tag-selector-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="!hasChanges">
        确定
      </el-button>
    </div>
    
    <!-- 创建标签对话框 -->
    <el-dialog
      v-model="tagDialogVisible"
      title="创建标签"
      width="500px"
    >
      <el-form
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagFormRules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <div class="color-picker-container">
            <el-color-picker v-model="tagForm.color" />
            <div class="preset-colors">
              <div
                v-for="color in presetColors"
                :key="color"
                class="preset-color"
                :style="{ backgroundColor: color }"
                @click="tagForm.color = color"
              ></div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="标签描述">
          <el-input
            v-model="tagForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createTag" :loading="saving">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { ElButton, ElIcon, ElInput, ElLoading, ElMessage, ElDialog, ElForm, ElFormItem, ElColorPicker } from 'element-plus';
import { Plus, Search, Check, Close } from '@element-plus/icons-vue';
import type { Tag } from '@/types';
import { tagService } from '@/services/tagService';
import EmptyState from '@/components/ui/EmptyState.vue';

// 组件属性
interface Props {
  modelValue?: string[]; // 已选择的标签ID列表
  multiple?: boolean; // 是否允许多选
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  multiple: true
});

// 组件事件
interface Emits {
  (e: 'update:modelValue', value: string[]): void;
  (e: 'confirm', value: string[]): void;
  (e: 'cancel'): void;
}

const emit = defineEmits<Emits>();

// 组件状态
const loading = ref(false);
const saving = ref(false);
const tags = ref<Tag[]>([]);
const selectedTags = ref<string[]>([...props.modelValue]);
const initialSelectedTags = ref<string[]>([...props.modelValue]);
const searchQuery = ref('');

// 标签对话框
const tagDialogVisible = ref(false);
const tagFormRef = ref();

// 标签表单
const tagForm = reactive({
  name: '',
  color: '#409EFF',
  description: ''
});

// 表单验证规则
const tagFormRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
};

// 预设颜色
const presetColors = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
  '#722ED1', '#EB2F96', '#FA541C', '#13C2C2', '#52C41A',
  '#1890FF', '#2F54EB', '#722ED1', '#F5222D', '#FA8C16'
];

// 计算属性：过滤后的标签
const filteredTags = computed(() => {
  if (!searchQuery.value) {
    return tags.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return tags.value.filter(tag => 
    tag.name.toLowerCase().includes(query) || 
    (tag.description && tag.description.toLowerCase().includes(query))
  );
});

// 计算属性：是否有变化
const hasChanges = computed(() => {
  if (selectedTags.value.length !== initialSelectedTags.value.length) {
    return true;
  }
  
  // 检查是否所有选中的标签都在初始选择中
  return !selectedTags.value.every(tagId => 
    initialSelectedTags.value.includes(tagId)
  );
});

// 加载标签列表
const loadTags = async () => {
  try {
    loading.value = true;
    const response = await tagService.getTags();
    tags.value = response.data;
  } catch (error) {
    ElMessage.error('加载标签失败');
    console.error('加载标签失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  // 搜索功能已在计算属性中实现
};

// 根据ID获取标签
const getTagById = (tagId: string): Tag | undefined => {
  return tags.value.find(tag => tag.id === tagId);
};

// 切换标签选择状态
const toggleTagSelection = (tagId: string) => {
  if (!props.multiple) {
    // 单选模式
    selectedTags.value = [tagId];
    return;
  }
  
  // 多选模式
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tagId);
  }
};

// 移除标签
const removeTag = (tagId: string) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  }
};

// 清除选择
const clearSelection = () => {
  selectedTags.value = [];
};

// 显示创建标签对话框
const showCreateDialog = () => {
  resetTagForm();
  tagDialogVisible.value = true;
};

// 重置标签表单
const resetTagForm = () => {
  tagForm.name = '';
  tagForm.color = '#409EFF';
  tagForm.description = '';
  
  // 重置表单验证
  if (tagFormRef.value) {
    tagFormRef.value.clearValidate();
  }
};

// 创建标签
const createTag = async () => {
  try {
    // 表单验证
    const valid = await tagFormRef.value.validate();
    if (!valid) return;
    
    saving.value = true;
    
    // 创建标签
    const newTag = await tagService.createTag({
      name: tagForm.name,
      color: tagForm.color,
      description: tagForm.description
    });
    
    ElMessage.success('标签创建成功');
    
    // 关闭对话框
    tagDialogVisible.value = false;
    
    // 添加到标签列表
    tags.value.push(newTag);
    
    // 自动选择新创建的标签
    selectedTags.value.push(newTag.id);
  } catch (error) {
    ElMessage.error('标签创建失败');
    console.error('创建标签失败:', error);
  } finally {
    saving.value = false;
  }
};

// 确认选择
const handleConfirm = () => {
  emit('update:modelValue', selectedTags.value);
  emit('confirm', selectedTags.value);
};

// 取消选择
const handleCancel = () => {
  // 恢复初始选择
  selectedTags.value = [...initialSelectedTags.value];
  emit('cancel');
};

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  selectedTags.value = [...newValue];
  initialSelectedTags.value = [...newValue];
});

// 组件挂载后加载标签
onMounted(() => {
  loadTags();
});
</script>

<style scoped lang="scss">
.tag-selector {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .tag-selector-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .tag-search {
    padding: 12px 16px;
  }
  
  .tag-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 16px;
    
    .tag-item {
      display: flex;
      align-items: center;
      padding: 10px 12px;
      margin-bottom: 6px;
      border-radius: 6px;
      cursor: pointer;
      transition: background-color 0.2s;
      
      &:hover {
        background-color: var(--el-color-primary-light-9);
      }
      
      &.tag-selected {
        background-color: var(--el-color-primary-light-8);
      }
      
      .tag-color {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        margin-right: 10px;
        flex-shrink: 0;
      }
      
      .tag-name {
        flex: 1;
        font-size: 14px;
      }
      
      .tag-check {
        margin-left: 8px;
        color: var(--el-color-primary);
      }
    }
  }
  
  .selected-tags {
    padding: 12px 16px;
    border-top: 1px solid var(--el-border-color-light);
    
    .selected-tags-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      span {
        font-size: 14px;
        font-weight: 500;
      }
    }
    
    .selected-tag-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .selected-tag-item {
        display: flex;
        align-items: center;
        padding: 4px 8px;
        background-color: var(--el-color-primary-light-9);
        border-radius: 16px;
        
        .tag-color {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          margin-right: 6px;
        }
        
        .tag-name {
          font-size: 12px;
          margin-right: 4px;
        }
        
        .el-button {
          padding: 2px;
          margin-left: 2px;
        }
      }
    }
  }
  
  .tag-selector-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    padding: 12px 16px;
    border-top: 1px solid var(--el-border-color-light);
  }
  
  .color-picker-container {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .preset-colors {
      display: flex;
      gap: 8px;
      
      .preset-color {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        cursor: pointer;
        transition: transform 0.2s;
        
        &:hover {
          transform: scale(1.2);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .tag-selector {
    .tag-selector-header {
      padding: 12px;
      
      h3 {
        font-size: 14px;
      }
    }
    
    .tag-search {
      padding: 8px 12px;
    }
    
    .tag-list {
      padding: 0 12px;
      
      .tag-item {
        padding: 8px 10px;
        
        .tag-color {
          width: 14px;
          height: 14px;
          margin-right: 8px;
        }
        
        .tag-name {
          font-size: 13px;
        }
      }
    }
    
    .selected-tags {
      padding: 8px 12px;
      
      .selected-tags-header {
        span {
          font-size: 13px;
        }
      }
      
      .selected-tag-list {
        .selected-tag-item {
          padding: 3px 6px;
          
          .tag-color {
            width: 10px;
            height: 10px;
            margin-right: 4px;
          }
          
          .tag-name {
            font-size: 11px;
          }
        }
      }
    }
    
    .tag-selector-actions {
      padding: 8px 12px;
    }
  }
}
</style>